import { HYEventStore } from 'hy-event-store'
import { getSongDetail, getSongLyric } from '../service/api_player'
import { parseLyric } from '../utils/parse-lyric'

// 创建播放器
// const audioContext = wx.createInnerAudioContext() //创建内部 audio 上下文
const audioContext=wx.getBackgroundAudioManager() //获取全局唯一的背景音频管理器。


const playerStore = new HYEventStore({
  state: {
    isFirstPlay:true,
    isStoping:false,

    id: 0,
    currentSong: {},
    durationTime: 0,
    lyricInfos: [],

    currentTime: 0,
    currentLyricText: "",
    currentLyricIndex: 1,

    isPlaying: false,

    playModeIndex: 0, //0：循环播放 1：单曲循环 2：随机播放
    songPlayList: [],
    songPlayListIndex: 0
  },
  actions: {
    //根据id播放音乐
    playMusicWithSongIdAction(ctx, { id ,isRefresh=false}) {
      //若非强制刷新，相同歌曲不会重复播放
      if (ctx.id == id && isRefresh==false) return
      ctx.id = id
      //修改播放状态,清空歌曲信息
      ctx.isPlaying = true
      ctx.currentSong = {}
      ctx.durationTime = 0
      ctx.lyricInfos = []
      ctx.currentTime = 0
      ctx.currentLyricIndex = 0
      ctx.currentLyricText = ""
      //请求歌曲详情
      getSongDetail(id).then(res => {
        const currentSong = res.data.songs[0]
        ctx.currentSong = currentSong
        ctx.durationTime = currentSong.dt
        audioContext.title=currentSong.name //背景音频标题设定
      })
      // 请求歌词数据
      getSongLyric(id).then(res => {
        const lyricString = res.data.lrc.lyric
        const lyric = parseLyric(lyricString)
        ctx.lyricInfos = lyric
      })
      //播放对应id的歌曲
      audioContext.stop()
      audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.name=id //音频标题暂定
      audioContext.autoplay = true
      //监听AudioContext相关事件
      if (ctx.isFirstPlay) {
         this.dispatch("setupAudioContextLinsterAction")
         ctx.isFirstPlay=false
      }
    },
    // 监听事件
    setupAudioContextLinsterAction(ctx) {
      // 1.监听音频进入可以播放状态
      audioContext.onCanplay(() => {
        audioContext.play()
      })
      // 2.监听时间改变
      audioContext.onTimeUpdate(() => {
        // 1.获取当前时间
        const currentTime = audioContext.currentTime * 1000
        // 2.根据当前时间修改currentTime
        ctx.currentTime = currentTime
        // 3.根据当前时间去查找播放的歌词
        if (!ctx.lyricInfos.length) return
        for (let i = 0; i < ctx.lyricInfos.length; i++) {
          const lyricInfo = ctx.lyricInfos[i]
          // 当前时间小于循环的歌词时间，显示上一行歌词
          if (currentTime < lyricInfo.time) {
            const currentIndex = i - 1
            //避免多次赋值，判断当前歌曲索引是否重合
            if (ctx.currentLyricIndex !== currentIndex) {
              const currentLyricInfo = ctx.lyricInfos[currentIndex]
              ctx.currentLyricIndex = currentIndex
              ctx.currentLyricText = currentLyricInfo.text
            }
            break;
          }
        }
      })
      // 监听音乐播放/暂停/停止/播放结束
      //播放状态
      audioContext.onPlay(()=>{
        ctx.isPlaying=true
      })
      // 暂停状态
      audioContext.onPause(()=>{
        ctx.isPlaying=false
      })
      //停止事件，关闭微信中的播放弹框
      audioContext.onStop(()=>{
        ctx.isPlaying=false
        ctx.isStoping=true
      })
      // 播放结束，切换下一首
      audioContext.onEnded(()=>{
        this.dispatch("changeNewMusicAction")
      }),
      //监听用户在系统音乐播放面板点击下一曲事件（仅iOS）
      audioContext.onNext(()=>{
        this.dispatch("changeNewMusicAction")
      })
      //监听用户在系统音乐播放面板点击上一曲事件（仅iOS)
      audioContext.onPrev(()=>{
        this.dispatch("changeNewMusicAction",false)
      })
    },

    // 切换播放状态
    changeMusicPlayStatusAction(ctx, isPlaying = true) {
      ctx.isPlaying = !isPlaying
      //当背景音频被关闭时，重新播放音乐
      if (ctx.isPlaying&&ctx.isStoping) {
        audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
        audioContext.name=ctx.currentSong.name
        ctx.isStoping=false
      }
      ctx.isPlaying ? audioContext.play() : audioContext.pause()
    },
    //切换下一首/上一首
    changeNewMusicAction(ctx,isNext=true) {
      // 1.获取当前索引
      let index = ctx.songPlayListIndex
      // 2.根据不同播放模式，获取下一首歌的索引
      switch (ctx.playModeIndex) {
        case 0: //顺序播放
          index = isNext?index + 1:index-1
          if (index === -1) index = ctx.songPlayList.length-1
          if (index === ctx.songPlayList.length) index = 0
          break
        case 1: //单曲循环
          break
        case 2://随机播放
          index = Math.floor(Math.random() * ctx.songPlayList.length)
          break
        //Math.random()产生0~1的随机数乘以列表长度6，而后进行Math.floor()向下取整
      }

      // 3.获取歌曲
      let currentSong = ctx.songPlayList[index]
      if (!currentSong) {
        currentSong = ctx.currentSong
      } else {
        //记录最新的索引
        ctx.songPlayListIndex = index
      }
      // 4.播放歌曲
      this.dispatch("playMusicWithSongIdAction", { id: currentSong.id ,isRefresh:true})
    },
  }
})

export {
  audioContext,
  playerStore,
}